﻿using System;
using System.Web.Security;
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Tenmah.DataAccess;

namespace Tenmah.Auth
{
    public class TenmahRoleProvider: RoleProvider
    {
        private string connectionString;
        private string pApplicationName;
        private IDbAdapter dbAdapter;

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            if (name == null || name.Length == 0)
                name = "TenmahRoleProvider";
            base.Initialize(name, config);
            if (config["applicationName"] == null || config["applicationName"].Trim() == "")
            {
                pApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            }
            else
            {
                pApplicationName = config["applicationName"];
            }
            connectionString = ConfigurationManager.ConnectionStrings[config["connectionStringName"]].ConnectionString;
        }

        public override string ApplicationName
        {
            get { return pApplicationName; }
            set { pApplicationName = value; }
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            foreach (string rolename in roleNames)
            {
                if (!RoleExists(rolename))
                {
                    throw new ProviderException("Role name not found.");
                }
            }

            foreach (string username in usernames)
            {
                if (username.Contains(","))
                {
                    throw new ArgumentException("User names cannot contain commas.");
                }

                foreach (string rolename in roleNames)
                {
                    if (IsUserInRole(username, rolename))
                    {
                        throw new ProviderException("User is already in role.");
                    }
                    dbAdapter.AddUserToRole(username, rolename);
                }
            }
        }

        public override void CreateRole(string roleName)
        {
            if (roleName.Contains(","))
            {
                throw new ArgumentException("Role names cannot contain commas.");
            }

            if (RoleExists(roleName))
            {
                throw new ProviderException("Role name already exists.");
            }
            dbAdapter.CreateRole(roleName);
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            if (!RoleExists(roleName))
            {
                throw new ProviderException("Role does not exist.");
            }

            if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0)
            {
                throw new ProviderException("Cannot delete a populated role.");
            }
            if (dbAdapter.DeleteRole(roleName))
                return true;
            else return false;
        }

        public override string[] GetAllRoles()
        {
            return dbAdapter.GetAllRoles();
        }

        public override string[] GetRolesForUser(string username)
        {
            return dbAdapter.GetRolesForUser(username);
        }

        public override string[] GetUsersInRole(string roleName)
        {
            return dbAdapter.GetUsersInRole(roleName);   
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            return dbAdapter.IsUserInRole(username, roleName);
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            foreach (string rolename in roleNames)
            {
                if (!RoleExists(rolename))
                {
                    throw new ProviderException("Role name not found.");
                }
            }

            foreach (string username in usernames)
            {
                foreach (string rolename in roleNames)
                {
                    if (!IsUserInRole(username, rolename))
                    {
                        throw new ProviderException("User is not in role.");
                    }
                    dbAdapter.RemoveUserFromRole(username, rolename);
                }
            }
        }

        public override bool RoleExists(string roleName)
        {
            return dbAdapter.RoleExists(roleName);
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            return dbAdapter.FindUsersInRole(roleName, usernameToMatch);
        }
    }
}
